const XLSX = require("xlsx");
import { formatDate, convertTime } from "@/utils/date"


const TYPE_ARRAY = [
  "前道",
  "后道",
  "前道plus"
];


// 经过评论反馈优化
function getCellWidth(value) {
  // 判断是否为null或undefined
  if (value == null) {
    return 10;
  } else if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
    // 中文的长度
    const chineseLength = value.match(/[\u4e00-\u9fa5]/g).length;
    // 其他不是中文的长度
    const otherLength = value.length - chineseLength;
    return chineseLength * 2.1 + otherLength * 1.1;
  } else {
    return value.toString().length * 1.1;
    /* 另一种方案
    value = value.toString()
    return value.replace(/[\u0391-\uFFE5]/g, 'aa').length
    */
  }
}




/**
 * 导出
 * @param {[]} list 
 * @param {[]} headers 
 */
export const fileExport = (list = []) => {
  // 定义列标题行
  const headers = ["公司名称", "日期", "时间", "地址", "员工", "行程时间"];

  const data = [];

  if (0 !== list.length) {
    list = list.filter((value, index, self) => {
      return self.indexOf(value) === index;
    });
    list.forEach((item) => {
      const { companyName, day, time, companyAddress, userName, duration } =
        item;
      data.push({
        公司名称: companyName,
        日期: formatDate(new Date(day * 1000), "yyyy/MM/dd"),
        时间: time,
        地址: companyAddress,
        员工: userName,
        行程时间: convertTime(duration),
      });
    });
  }

  commonExport("派单历史-", "日期", data, headers, "时间");


};

/**
 * 导出阅览
 * @param {[]} list 
 * @param {number} type 
 */
export const fileReadExport = (list = [], type) => {
  // 定义列标题行
  const readHeaders = ["公司编号", "城市", "日期", "出单人", "员工",];

  const data = [];

  console.log("this.list", list.length);

  if (0 !== list.length) {
    list = list.filter((value, index, self) => {
      return self.indexOf(value) === index;
    });

    list.forEach((item) => {

      if (type == item.type) {
        const { enterpriseId, day, time, city, userName, seller } =
          item;
        data.push({
          公司编号: enterpriseId,
          城市: city,
          日期: formatDate(new Date(day * 1000), "yyyy/MM/dd"),
          出单人: seller,
          员工: userName,
        });
      }
    });
  }

  console.log("type", type);

  commonExport("派单结果-" + TYPE_ARRAY[type] + "-", "日期", data, readHeaders);
};

function commonExport(name, timeKey, data = [], headers = []) {

  const headerStyle = {
    font: { bold: true },
    fill: { patternType: "solid", fgColor: { rgb: "FFFF00" } },
    alignment: { horizontal: "center" },
  };
  // 创建工作簿和工作表
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(data, { header: headers, headerStyle: headerStyle });

  let colWidths = [],
    colNames = Object.keys(data[0]) // 所有列的名称数组

  // 计算每一列的所有单元格宽度
  // 先遍历行
  data.forEach((row, index) => {
    // 遍历列
    for (const key in row) {
      if (colWidths[index] == null) colWidths[index] = []

      switch (typeof row[key]) {
        case 'string':
        case 'number':
        case 'boolean':
          colWidths[index].push(getCellWidth(row[key]))
          break
        case 'object':
        case 'function':
          colWidths[index].push(0)
          break
      }
    }
  })

  worksheet['!cols'] = []
  // 每一列取最大值最为列宽
  colWidths.forEach((widths, index) => {
    // 计算列头的宽度
    widths.push(getCellWidth(colNames[index]))
    // 设置最大值为列宽
    console.log("widths", widths);
    worksheet['!cols'].push({ wch: Math.max(...widths) })
  })



  // worksheet['!cols'] = [
  //   { wpx: 80 },
  //   { wch: 40 },
  //   { width: 30 }
  // ]

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");


  // 导出为Excel文件
  XLSX.writeFile(workbook, data.length ? name + data[0][timeKey] + '.xlsx' : "data.xlsx");
}

/**
 * 
 */
